import React, {Component} from 'react';
import Cookie from 'universal-cookie';
import {Redirect, withRouter} from "react-router-dom";
import jwt from 'jsonwebtoken';
import {JWT_SECRET} from "../config/jwt";
import {USERINFO_KEY, USER_TOKEN_COOKIE_KEY} from "../config/setting";

class Authenticated extends Component {
    state = {
        token: null,
    };

    static getDerivedStateFromProps(props, state) {
        const cookie = new Cookie();
        const auth = cookie.get(USER_TOKEN_COOKIE_KEY);

        if (!auth) {
            sessionStorage.removeItem(USERINFO_KEY);
            return {token: auth};
        }

        const userInfo = sessionStorage.getItem(USERINFO_KEY);

        if (userInfo && JSON.parse(userInfo).tok !== auth.slice(-16)) {
            sessionStorage.removeItem(USERINFO_KEY);
        }

        if (!sessionStorage.getItem(USERINFO_KEY)) {
            try {
                const payload = jwt.verify(auth, JWT_SECRET);

                sessionStorage.setItem(USERINFO_KEY, JSON.stringify({tok: auth.slice(-16), ...payload}));
            } catch (e) {
                sessionStorage.removeItem(USERINFO_KEY);

                return {token: null};
            }
        }

        return {token: auth};
    };

    render() {
        if (!this.state.token) {
            return <Redirect to={'/login?r=' + this.props.location.pathname}/>;
        }

        return (
            this.props.children
        );
    }
}

export default withRouter(Authenticated);